/**
 * @file ClassStudents.vue
 * @description 班级学生成绩页面，展示选中班级的所有学生及其成绩信息
 * @created 2024-05-10
 */

<template>
  <div class="class-students-container">
    <div class="class-header">
      <div class="back-btn" @click="$router.go(-1)">
      <span class="icon">←</span> 返回
      </div>
      <div class="class-info-content" v-if="pageData.class_name">
        <h1>{{ pageData.class_name }} - {{ pageData.course_name }}</h1>
        <p>教师: {{ pageData.teacher_name }} | 学期: {{ pageData.semesters }}</p>
      </div>
      <el-skeleton :rows="2" animated v-else />
    </div>

    <div class="stats-section" v-if="pageData.stats">
      <el-row :gutter="15">
        <el-col :xs="12" :sm="8" :md="4" v-for="(value, key) in statLabels" :key="key">
          <div class="stat-card">
            <div class="stat-value">
              {{ formatStatValue(pageData.stats[key], key) }}
        </div>
            <div class="stat-label">{{ value }}</div>
          </div>
        </el-col>
      </el-row>
        </div>
    <el-skeleton :rows="1" animated v-else-if="loading" class="stats-skeleton" />
      
    <div class="charts-section" v-if="pageData.score_distribution">
        <el-card shadow="never">
            <template #header>
                <div class="card-header">
                    <span>成绩分布</span>
      </div>
            </template>
            <div ref="scoreDistributionChart" style="height: 300px;"></div>
        </el-card>
    </div>

    <div class="students-table-section">
      <div class="table-header">
        <h2>学生成绩列表</h2>
        <el-input
          v-model="searchText"
          placeholder="搜索学生姓名或学号..."
          clearable
          prefix-icon="el-icon-search"
          style="width: 250px;"
        />
      </div>
      <el-table 
        v-loading="loading"
        :data="filteredStudents"
        style="width: 100%"
        empty-text="暂无学生成绩数据"
        border
      >
        <el-table-column prop="rank" label="排名" width="80" align="center" />
        <el-table-column prop="student_id" label="学号" width="150" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="gender" label="性别" width="80" align="center" />
        <el-table-column label="成绩" prop="score" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getScoreTagType(scope.row.score)">
              {{ scope.row.score !== null ? scope.row.score.toFixed(1) : '-' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="120" align="center">
            <template #default="scope">
                <el-button size="small" @click="viewStudentDetail(scope.row.student_id)">查看详情</el-button>
            </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { getClassCourseStudentScores } from '@/api/admin/teacheradmin/teacher';
import * as echarts from 'echarts';

export default {
  name: 'ClassStudents',
  data() {
    return {
      teacherId: this.$route.params.teacherId,
      courseId: this.$route.params.courseId,
      classId: this.$route.params.classId,
      pageData: { // Will be populated by API
        teacher_name: this.$route.query.teacherName || '',
        course_name: this.$route.query.courseName || '',
        class_name: this.$route.query.className || '',
        semesters: '',
        stats: null,
        score_distribution: null,
        students: []
      },
      loading: true,
      searchText: '',
      statLabels: {
        student_count: '学生总数',
        avg_score: '平均分',
        max_score: '最高分',
        min_score: '最低分',
        pass_rate: '及格率',
        excellent_rate: '优秀率'
      },
      scoreDistributionChartInstance: null,
    };
  },
  computed: {
    filteredStudents() {
      if (!this.searchText) {
        return this.pageData.students;
      }
      return this.pageData.students.filter(student =>
        student.name.toLowerCase().includes(this.searchText.toLowerCase()) ||
        student.student_id.toLowerCase().includes(this.searchText.toLowerCase())
      );
    }
  },
  created() {
    this.fetchClassStudentScoresData();
  },
  mounted() {
    // Chart initialization moved to watch or after data fetch
  },
  beforeUnmount() {
    if (this.scoreDistributionChartInstance) {
      this.scoreDistributionChartInstance.dispose();
    }
  },
  watch: {
    'pageData.score_distribution': function(newVal) {
      if (newVal) {
        this.initScoreDistributionChart();
  }
}
  },
  methods: {
    async fetchClassStudentScoresData() {
      this.loading = true;
      try {
        const response = await getClassCourseStudentScores(this.teacherId, this.courseId, this.classId);
        if (response.status === 'success' && response.data) {
          this.pageData = response.data;
        } else {
          this.$message.error(response.message || '获取学生成绩信息失败');
        }
  } catch (error) {
        console.error('获取学生成绩信息失败:', error);
        this.$message.error('获取学生成绩信息失败，请检查网络连接');
  } finally {
        this.loading = false;
  }
    },
    formatStatValue(value, key) {
      if (value === null || value === undefined) return '-';
      if (key === 'pass_rate' || key === 'excellent_rate') {
        return `${value.toFixed(1)}%`;
      }
      if (typeof value === 'number' && key !== 'student_count') {
        return value.toFixed(1);
      }
      return value;
    },
    getScoreTagType(score) {
      if (score === null || score === undefined) return 'info';
      if (score >= 90) return 'success';
      if (score >= 80) return 'primary';
      if (score >= 70) return 'warning';
      if (score >= 60) return 'danger';
      return 'info';
    },
    viewStudentDetail(studentId){
        // Placeholder for navigating to a student's detailed page if needed
        this.$message.info(`查看学生 ${studentId} 的详细信息 (功能待实现)`);
    },
    initScoreDistributionChart() {
      if (this.scoreDistributionChartInstance) {
        this.scoreDistributionChartInstance.dispose();
      }
      const chartDom = this.$refs.scoreDistributionChart;
      if (chartDom && this.pageData.score_distribution) {
        this.scoreDistributionChartInstance = echarts.init(chartDom);
        const option = {
  tooltip: {
            trigger: 'item'
  },
  legend: {
            top: '5%',
            left: 'center'
  },
  series: [
    {
              name: '成绩分布',
      type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
      emphasis: {
                label: {
                  show: true,
                  fontSize: '20',
                  fontWeight: 'bold'
        }
      },
              labelLine: {
                show: false
              },
              data: this.pageData.score_distribution.categories.map((cat, index) => ({
                value: this.pageData.score_distribution.values[index],
                name: cat
              }))
    }
  ]
        };
        this.scoreDistributionChartInstance.setOption(option);
      }
    }
  }
};
</script>

<style scoped>
.class-students-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 80px);
}

.class-header {
  position: relative;
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  margin-bottom: 20px;
  min-height: 80px;
}

.back-btn {
  position: absolute;
  top: 20px;
  left: 20px;
  cursor: pointer;
  color: #409EFF;
  display: flex;
  align-items: center;
}

.icon {
  font-size: 18px;
  margin-right: 5px;
}

.class-info-content {
  text-align: center;
  padding: 10px 0;
}

.class-info-content h1 {
  margin-bottom: 8px;
  font-size: 22px;
}

.class-info-content p {
  margin: 4px 0;
  color: #606266;
  font-size: 14px;
}

.stats-section {
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
    margin-bottom: 20px;
}
.stats-skeleton {
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
    margin-bottom: 20px;
    height: 70px; /* Approximate height of a single stat card row */
}

.stat-card {
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
  text-align: center;
  border: 1px solid #e0e0e0;
  margin-bottom: 15px; /* For smaller screens where they stack */
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 13px;
  color: #909399;
}

.charts-section {
    margin-bottom: 20px;
}

.students-table-section {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.table-header h2 {
  font-size: 18px;
  margin: 0;
}

.el-table {
  margin-top: 10px;
}
</style> 